/*
 * @Author: lmh
 * @Date: 2021-09-05 13:14:44
 * @LastEditTime: 2021-09-05 15:21:13
 * @LastEditors: lmh
 * @Description: 手动实现promise
 */
class Promise {
    constructor(executor) {
        this.status = 'pending'; // 状态
        this.value = undefined; // 成功时返回的值
        this.reason = undefined; // 失败时返回的值
        this.onResolvedCallbacks = []; // 存放成功的回调
        this.onRejectedCallbacks = []; // 存放失败的回调

        let resolve = (data) => {
            if (this.status === 'pending') {
                this.value = data;
                this.status = 'resolved';
                this.onResolvedCallbacks.forEach(fn => fn())
            }
        }
        let reject = (reason) => {
            if (this.status === 'pending') {
                this.reason = reason;
                this.status = 'rejected';
                this.onRejectedCallbacks.forEach(fn => fn())
            }
        }

        // 执行时发生异常，回调 reject()函数
        try {
            executor(resolve, reject);
        } catch (e) {
            reject(e)
        }
    }
    then(onFuiFilled, onRejected) {
        if (this.status === 'resolved') {
            onFuiFilled(this.value)
        }
        if (this.status === 'rejected') {
            onRejected(this.reason)
        }
        if (this.status === 'pending') { // TODO
            this.onResolvedCallbacks.push(() => {
                onFuiFilled(this.value)
            })
            this.onRejectedCallbacks.push(() => {
                onRejected(this.reason)
            })
        }
    }
}
Promise.all = function (promises) {
    return new Promise(function (resolve, reject) {
        let arr = []; // 最终返回值的结果
        let i = 0; // 表示成功了次数
        function processData(index, data) {
            arr[index] = data;
            if (++i === promises.length) {
                resolve(arr);
            }
        }
        for (let i = 0; i < promises.length; i++) {
            promises[i].then(function (data) {
                processData(i, data)
            }, reject)
        }
    })
}
Promise.race = function (promises) {
    return new Promise((resolve, reject) => {
        for (var i = 0; i < promises.length; i++) {
            promises[i].then(resolve, reject)
        }
    })
}

// 生成一个成功的promise
Promise.resolve = function(value){
    return new Promise((resolve,reject) => resolve(value));
}
// 生成一个失败的promise
Promise.reject = function(reason){
    return new Promise((resolve,reject) => reject(reason));
}

module.exports = Promise;
